package top.api.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.api.common.RedisKey;
import top.api.common.ResUlt;
import top.api.domain.dto.SysUserLoginDto;
import top.api.domain.pojo.User;
import top.api.mapper.UserMapper;
import top.api.service.loginUserService;
import top.api.utils.RedisCache;

import javax.annotation.Resource;

@Service
@RequiredArgsConstructor
public class loginUserServiceImpl implements loginUserService {
    private  final UserMapper baseMapper;

    private final RedisCache redisCache;
    @Override
    public ResUlt<Object> login(SysUserLoginDto sysUserLoginDto) {
        // 查询验证码是否正确, 无论正确错误都把验证码删除
        String picCode = redisCache.getCacheObject(RedisKey.getPicCodeKey() + ":" + sysUserLoginDto.getUuid());
        if (!sysUserLoginDto.getPicCode().equals(picCode)) {
            redisCache.deleteObject(RedisKey.getPicCodeKey() + ":" + sysUserLoginDto.getUuid());
            return ResUlt.error("图片验证码错误!");
        }
        redisCache.deleteObject(RedisKey.getPicCodeKey() + ":" + sysUserLoginDto.getUuid());

        // 查询账号信息是否存在
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, sysUserLoginDto.getUserName());
        queryWrapper.eq(User::getPassword,sysUserLoginDto.getPassword());

        User user = baseMapper.selectOne(queryWrapper);

        if (ObjectUtils.isEmpty(user)) {
            return ResUlt.error("账号或密码错误!");
        }

        // 查询是否被冻结
        if (user.getStatus().equals("1")) {
            return ResUlt.error("账号异常!");
        }

        // 记录ip
//        user.setIp(request.getRemoteAddr());
//        baseMapper.updateById(user);

        StpUtil.login(user.getId(), true);

        String tokenValue = StpUtil.getTokenValue();
        String loginId = StpUtil.getLoginId().toString();
        System.out.println(loginId);
        return ResUlt.success("登录成功", tokenValue);

    }
}
